import CryptoJS from "crypto-js/crypto-js";
import config from "../config.js";
import routeUtils from "../ext/routeUtils.js";
import Request from "@/ext/http.js";
import store from "@/store/index.js"
var userActiveNotice;
import cryptoJs from 'crypto-js'
const $request = Request.mgHttp
// 自定义toast
function toast(tit, icon = "none", duration=2000) {
	uni.showToast({
		title: tit,
		mask: false,
		duration: duration,
		icon: icon
	});
}

// HMACSHA256加密
function HmacSHA256(message, key) {
	let hash = CryptoJS.HmacSHA256(message, key).toString();
	return hash;
}

// sha256加密
function sha256(message) {
	let hash = CryptoJS.SHA256(message).toString();
	return hash;
}

//同一处理LinkValue
function handleLink(linkType, linkValue, ...params) {
	console.log("linkType", linkType);
	console.log("linkValue", linkValue);
	console.log("params", params);
	linkType = linkType + ''
	var shopId = "";
	if (params.length > 0 && params[0].shopId) {
		shopId = params[0].shopId;
	}
	var mParams = null;
	if (params.length > 0 && params[0]) {
		var obj = {
			linkValue: params[0].linkValue,
			linkType: params[0].linkType
		};
		if (params[0].categoryName) {
			obj.categoryName = params[0].categoryName;
		} else if (params[0].entryName) {
			obj.entryName = params[0].entryName;
		} else if (params[0].title || params[0].supplierTitle) {
			obj.title = params[0].title || params[0].supplierTitle;
		} 
	  // 指定供应商中品牌跟分类可以指定
		if (params[0].brandType == 2) obj.brandIdList = params[0].brandIdList
		if (params[0].categoryType == 2) obj.categoryIdList = params[0].categoryIdList
		mParams = JSON.stringify(obj);
	}
	var statInfo = {
		'Ref_Module_Type': linkType,
		'Ref_Module_ID': linkValue
	};
	if (params.length > 1 && params[1].statInfo) { //埋点数据
		statInfo = params[1].statInfo
	}
	let newGoodsInfo;
	if (params && params.length && params[0].isShowNewGoods !== undefined) {
		newGoodsInfo = JSON.stringify(params[0])
	}else {
		newGoodsInfo = JSON.stringify({})
	}
	switch (
		linkType //104	会员专区活动ID  	100	商品组ID
	) {
		case "100": //100	商品组ID
			console.log("商品组:", params);
			// routeUtils.navigateTo({
			// 	url: "/package_page/productListSearch?linkValue=" + linkValue + '&params=' + mParams
			// });
			if (!shopId) {
				routeUtils.navigateTo({
					url: "/package_goods/search/search?linkValue=" +
						linkValue +
						"&params=" +
						mParams
				}, statInfo);
			} else {
				routeUtils.navigateTo({
					url: "/package_goods/search/search?linkValue=" +
						linkValue +
						"&params=" +
						mParams +
						"&shopId=" +
						shopId
				}, statInfo);
			}

			break;
		case "101": //商品详情	101	商品ID
			routeUtils.navigateTo({
				url: "/pages/goods/detail?spuId=" + linkValue
			}, statInfo);
			break;
		case "102": //商品分类	102	商品分类数组
			if (typeof linkValue == "string") {
				linkValue = JSON.parse(linkValue);
			}
			if (!shopId) {
				routeUtils.navigateTo({
					url: `/package_goods/category/category-special?linkValue=${linkValue.join(",")}&newGoodsInfo=${newGoodsInfo}`
				}, statInfo);
			} else {
				routeUtils.navigateTo({
					url: `/package_goods/category/category-special?linkValue=${linkValue.join(",")}&shopId=${shopId}&newGoodsInfo=${newGoodsInfo}`
				}, statInfo);
			}

			break;
		case "103": //关键词搜索	103	关键字
			if (!shopId) {
				routeUtils.navigateTo({
					url: "/package_goods/search/search?hotSearchKeyWord=" +
						linkValue +
						"&params=" +
						mParams
				}, statInfo);
			} else {
				routeUtils.navigateTo({
					url: "/package_goods/search/search?hotSearchKeyWord=" +
						linkValue +
						"&shopId=" +
						shopId +
						"&params=" +
						mParams
				}, statInfo);
			}
			break;
		case "104": //商城内部模块
			routeUtils.navigateTo({
				url: linkValue
			}, statInfo);
			break;
		case "105": //URL地址
			if (insideUrl(linkValue, statInfo)) {
				return
			};
			if (linkValue.includes("m.migudm.cn/spa/member/index.html")) { //会员中心页面单独处理
				this.jumpToUser();
				return
			}

			if (
				store.state.entrance == "app" &&
				!store.state.isSDK
			) {
				let linkUrl = linkValue;
				//如果是客户端且非SDK，走deeplink链接
				if ((linkUrl.includes("m.migudm.cn") || linkUrl.includes("cx.migudm.cn") || linkUrl.includes(
						"g.10086.cn")) &&
					store.state.token) {
					//如果实际链接是门户，需走同步登录，否则直接跳转
					navigateToWithSSO(linkValue);
				} else {
					if (linkValue.match(/migudm\.cn.*pageType=webView/)) {
						routeUtils.locationTo(linkValue)
					} else {
						routeUtils.locationTo("https://m.migudm.cn?pageType=webView&url=" +
							encodeURIComponent(linkValue))
					}
				}
			} else {
				//如果是小程序或h5
				//先获取跳转链接，如果链接时deeplink形式，则把实际跳转链拿出
				let linkUrl = linkValue;
				if (linkUrl.match(/migudm\.cn.*pageType=webView/)) {
					linkUrl = decodeURIComponent(linkUrl.match("url=([^&]+)")[1]);
				}
				//圈圈活动页 需要在小程序需要加 miniprogram=mgmall
				if (store.state.entrance == "mp-weixin" && linkUrl.includes("m.migudm.cn")) {
					if (linkUrl.indexOf("?") != -1) {
						linkUrl = linkUrl + "&miniprogram=mgmall"
					} else {
						linkUrl = linkUrl + "?miniprogram=mgmall"
					}
				}
				//如果实际链接是门户，则走同步登录，否则直接跳转 咪咕day地址增加跳转
				if ((linkUrl.includes("m.migudm.cn") || linkUrl.includes("cx.migudm.cn") || linkUrl.includes(
						"g.10086.cn")) &&
					store.state.token) {
					navigateToWithSSO(linkUrl);
				} else {
					if (store.state.entrance == "mp-weixin") {
						if (linkUrl.indexOf('docs.qq.com')>-1) {
							wx.navigateToMiniProgram({
								appId: 'wxd45c635d754dbf59',
								path: `pages/detail/detail?url=${encodeURIComponent(linkUrl)}`
							})
							return
						} else if (linkUrl.startsWith('/')) {
							routeUtils.navigateTo({
								url: linkUrl
							});
							return
						}
						var enCodeUrl = encodeURIComponent(linkUrl);
						routeUtils.navigateTo({
							url: "/pages/tools/webView?enCode=1&webUrl=" + enCodeUrl
						});
					} else {
						routeUtils.locationTo(linkUrl)
					}
				}
			}
			break;
		case "106": // 页面 ID
			if (params && params.length && params[0].pageType) {
				const pageType = params[0].pageType
				if (pageType == 10) {
					goToMgVideo(linkValue)
				} else {
					routeUtils.navigateTo({
						url: "/package_activity/customize/index?pageId=" + linkValue
					}, statInfo);
				}
			} else {
				routeUtils.navigateTo({
					url: "/package_activity/customize/index?pageId=" + linkValue
				}, statInfo);
			}
			break
		case "110":
		case "111":
			routeUtils.navigateTo({
				url: "/package_activity/customize/index?pageId=" + linkValue
			}, statInfo);
			break;
		case "107": // 商品IP ID
			if (!shopId) {
				routeUtils.navigateTo({
					url: `/package_goods/category/category-special?linkType=107&newGoodsInfo=${newGoodsInfo}&linkValue=${linkValue}`
				}, statInfo);
			} else {
				routeUtils.navigateTo({
					url: `/package_goods/category/category-special?linkType=107&newGoodsInfo=${newGoodsInfo}&linkValue=${linkValue}&shopId=${shopId}`
				}, statInfo)
			}

			break;
		case "112": // 跳转店铺首页
			routeUtils.navigateTo({
				url: "/package_shop/index?shopId=" + linkValue
			}, statInfo);
			break;
		case "113": // 跳转圈圈直播间
			if (
				store.state.entrance == "app" &&
				!store.state.isSDK
			) {
				//如果是客户端且非SDK，走deeplink链接
				window.location.href =
					"https://m.migudm.cn?pageType=liveAudienceDetail&anchorId=" +
					linkValue;
			} else {
				//如果是小程序或h5
				routeUtils.locationTo("https://m.migudm.cn/client/allLive/?anchorId=" + linkValue)
			}
			break;
		case "114": // 跳转微信小程序直播间
			let roomId = [linkValue];
			let customParams = encodeURIComponent(
				JSON.stringify({
					path: "pages/index/index",
					pid: 1
				})
			);
			wx.navigateTo({
				url: `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${roomId}&custom_params=${customParams}`
			});
			break;
		case "115": // 跳转潮物说内容推荐页
			break;
		case '116': // 课程分类
		case '117': // 课程标签
				var mLinkValue = JSON.stringify(linkValue)
			routeUtils.navigateTo({
				url: '/package_course/list/moreCourseList?linkType='+linkType+'&linkValue=' + mLinkValue
			}, statInfo)
			break;
		case '118': // 指定课程
			if(linkValue.length == 1){
				routeUtils.navigateTo({
					url: `/pages/goods/detail?spuId=${linkValue}`
				}, statInfo)
			}else if(linkValue.length > 1){
				var mLinkValue = JSON.stringify(linkValue)
				routeUtils.navigateTo({
					url: '/package_course/list/moreCourseList?linkType=118&linkValue=' + mLinkValue
				}, statInfo)
			}
			break;
		case "121": // 供应商
			routeUtils.navigateTo({
				url: "/package_goods/search/search?linkValue=" +
					linkValue +
					"&params=" +
					mParams
			}, statInfo);
			break;
		case "122": // 品牌
			const bandParam = JSON.parse(mParams)
			const url = `/package_goods/category/category-special?linkType=brandId&linkValue=${linkValue}&params=${mParams}`
			routeUtils.navigateTo({
				url,
			}, statInfo);
			break;
		case "123": // 多选一，疗休养
			routeUtils.navigateTo({
				url: `/package_activity/rest/index?activityId=${linkValue}`,
			}, statInfo);
			break;
		case "131": // 领取优惠券
			if(params[2]){
				routeUtils.navigateTo({
					url: "/package_activity/coupon/list?fragmentId=" + params[2]
				}, statInfo);
			}
			break;
		case "130": // 优惠券引流页
			routeUtils.navigateTo({
				url: "/package_activity/coupon/marketing-page?pageId=" + linkValue
			}, statInfo);
			break;
		case "124": // 返回场景首页
			routeUtils.reLaunch({
				url: `/pages/index/index`,
			}, statInfo);
			break;
	}
}
/**
 * 内部url路径跳转
 * @param {Object} url
 */
function insideUrl(url, statInfo) {
	try {
		var domainUrl = "mgmall.migudm.cn";
		if (config.env == "test") { //兼容测试环境
			domainUrl = "112.48.155.25:18080"
		} else if (config.env == "release") { //兼容预上线环境
			domainUrl = "mgmall.migudm.cn"
		}
		domainUrl += config.basePath
		if (url.includes(domainUrl) && !url.includes((domainUrl + "/mallb")) && !url.includes((domainUrl + "/mallc")) &&
			!url.includes((domainUrl + "/activity"))) {
			var list = url.split(domainUrl);
			console.log('list', list);
			routeUtils.navigateTo({
				url: '/' + list[1]
			}, statInfo);
			return true
		} else {
			return false
		}
	} catch (e) {
		//TODO handle the exception
		return false
	}
}
/**判断是否是手机号**/
function isPhoneNumber(tel) {
	var reg = /^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/;
	return reg.test(tel);
}
/**
 * 判断邮箱格式
 * @param {Object} email
 */
function isEmail(email) {
	var reg =
		/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	return reg.test(email);
}

/**判断是否是邮编**/
function isPostcode(code) {
	var reg = /^[1-9]\d{5}$/;
	return reg.test(code);
}

/**
 * iOS适配问题 页面滚动
 */
function checkWxScroll() {
	let entrance = store.state.entrance;
	console.log("checkWxScroll");
	//微信小程序不需要处理
	if (entrance != "mp-weixin") {
		var u = navigator.userAgent;
		var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
		if (isiOS) {
			//如果iphone版本号>=12
			var currentPosition, timer;
			var speed = 1; //页面滚动距离
			timer = setInterval(function() {
				currentPosition =
					document.documentElement.scrollTop || document.body.scrollTop;
				currentPosition -= speed;
				window.scrollTo(0, currentPosition); //页面向上滚动
				currentPosition += speed; //speed变量
				window.scrollTo(0, currentPosition); //页面向下滚动
				clearInterval(timer);
			}, 1);
		}
	}
}

//获取URL的参数
function getRequest() {
	var url = location.search; //获取url中"?"符后的字串
	var theRequest = new Object();
	if (url.indexOf("?") != -1) {
		var str = url.substr(1);
		var strs = str.split("&");
		for (var i = 0; i < strs.length; i++) {
			theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
		}
	}
	return theRequest;
}

//退出登录
function logout() {
	store.commit("clearLoginInfo");
	clearInterval(userActiveNotice);
	if (store.state.entrance == 'mp-weixin') {
		routeUtils.reLaunch({
			url: "/pages/index/index"
		});
	}
}

//按数值规范格式化数值
function formatNum(num) {
	num = num + ""; // 转为字符串
	if (num > 10000 && num < 100000000) {
		num = (num / 10000).toFixed(1);
		if (/\d*\.0/.test(num)) {
			num = num.replace(/\.0/, "");
		}
		num = num
			.split("")
			.reverse()
			.join("")
			.replace(/(\d{3})\B/g, "$1,")
			.split("")
			.reverse()
			.join("");
		num = num + "w";
	} else if (num >= 100000000) {
		num = (num / 10000).toFixed(1);
		if (/\d*\.0/.test(num)) {
			num = num.replace(/\.0/, "");
		}
		num = num
			.split("")
			.reverse()
			.join("")
			.replace(/(\d{3})\B/g, "$1,")
			.split("")
			.reverse()
			.join("");
		num = num + "w";
	} else {
		num = num
			.split("")
			.reverse()
			.join("")
			.replace(/(\d{3})\B/g, "$1,")
			.split("")
			.reverse()
			.join("");
	}

	return num;
}

//时间字符串格式化
function formatTime(timeStr, join = "/", type) {
	try {
		timeStr = timeStr.toString();
		let y = timeStr.slice(0, 4);
		let m = timeStr.slice(4, 6);
		let d = timeStr.slice(6, 8);
		let h = timeStr.slice(8, 10);
		let mm = timeStr.slice(10, 12);
		let s = timeStr.slice(12, 14);
		// let ss = timeStr.slice(14, 17);
		if (join == "md") {
			return m + "月" + d + "日" + " " + h + ":" + mm;
		} else if (join == "mds") {
			return m + "." + d + " " + " " + h + ":" + mm;
		} else {
			return y + join + m + join + d + " " + h + ":" + mm + ":" + s;
		}
	} catch (e) {
		//TODO handle the exception
		return timeStr
	}
}

//获取微信code用来去后台获取openid
function getWxCode() {
	return new Promise((resolve, reject) => {
		wx.login({
			success: function(res) {
				console.log("wxcode:" + res.code);
				resolve(res.code);
			},
			fail: function(loginError) {
				reject(false);
				toast("获取微信code失败");
			}
		});
	});
}

//封装session只对h5有效，其他端还是localStorage
function setSession(valueObj) {
	if (store.state.entrance == "mp-weixin") {
		for (let key in valueObj) {
			setSession(key, valueObj[key]);
		}
	} else {
		for (let key in valueObj) {
			uni.setStorageSync(key, valueObj[key]);
		}
	}
}

function getSession(key) {
	if (store.state.entrance == "mp-weixin") {
		return getSession(key);
	} else {
		return uni.getStorageInfoSync(key);
	}
}

function clearSession(...keyArr) {
	if (store.state.entrance == "mp-weixin") {
		for (let key of keyArr) {
			clearSession(key);
		}
	} else {
		for (let key in keyArr) {
			uni.removeStorageSync(key);
		}
	}
}

/**图片压缩处理
 * @param {Object} path
 * @param {Object} obj
 * @param {Object} callback
 * @param {String} String 第几组
 */
function canvasDataURL(path, obj, index) {
	console.log("canvasDataURL:", path, obj);
	return new Promise((resolve, reject) => {
		var img = new Image();
		img.src = path;
		img.onload = function() {
			var that = this;
			// 默认按比例压缩
			var w = that.width,
				h = that.height,
				scale = w / h;
			w = obj.width || w;
			h = obj.height || w / scale;
			var quality = 0.7; // 默认图片质量为0.7
			//生成canvas
			var canvas = document.createElement("canvas");
			var ctx = canvas.getContext("2d");
			// 创建属性节点
			var anw = document.createAttribute("width");
			anw.nodeValue = w;
			var anh = document.createAttribute("height");
			anh.nodeValue = h;
			canvas.setAttributeNode(anw);
			canvas.setAttributeNode(anh);
			ctx.drawImage(that, 0, 0, w, h);
			// 图像质量
			if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
				quality = obj.quality;
			}
			// quality值越小，所绘制出的图像越模糊
			var base64 = canvas.toDataURL("image/jpeg", quality);
			// 回调函数返回base64的值

			resolve({
				file: base64,
				path,
				index
			});
		};
	})
}
//将base64转换为blob
function dataURLtoBlob(dataurl) {
	var arr = dataurl.split(","),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}
//将blob转换为file
function blobToFile(theBlob, fileName) {
	theBlob.lastModifiedDate = new Date();
	theBlob.name = fileName;
	return theBlob;
}

function backFresh(homeType = 'index') {
	var homeUrl = "/pages/index/index"
	// 缓存中如果存在首页则更改首页地址
	if (store.state.scene.homePageUrl) homeUrl = store.state.scene.homePageUrl
	var pages = getCurrentPages();
	// alert("getCurrentPages:"+pages.length);
	if (pages.length == 1) {
		// #ifdef  H5
		let returnLayerUrl = store.state.scene.returnLayerUrl;
		if (returnLayerUrl) {
			handleLink('105', returnLayerUrl);
			return
		}
		let pageHistory = window.history
		if (pageHistory.length > 1) { //如果浏览器历史有,走浏览器返回
			pageHistory.back()
			return
		}
		// #endif

		// #ifdef  H5
		if (
			store.state.entrance == "app" &&
			location.href.indexOf("backHome=1") > 0
		) {
			routeUtils.reLaunch({
				url: homeUrl
			});
		} else {
			// referrer 属性返回载入当前文档的来源文档的URL。如果当前文档不是通过超级链接访问的，则为 null。
			if (document.referrer === '') {
				routeUtils.reLaunch({
					url: homeUrl
				});
			} else {
				window.history.back(-1);
			}
		}
		// #endif
		// #ifdef  MP-WEIXIN
		homeUrl = '/pages/user/benefits'
		routeUtils.reLaunch({
			url: homeUrl
		});
		// #endif
	} else {
		uni.navigateBack()
	}
}

/**
 * 无中划线的uuid
 */
function getRandomStr() {
	var d = new Date().getTime();
	var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(
		c
	) {
		var r = (d + Math.random() * 16) % 16 | 0;
		d = Math.floor(d / 16);
		return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
	});

	uuid = uuid.split("-").join("");
	return uuid;
}

function generCookieId() {
	let dateObj = new Date();
	let month = dateObj.getMonth() + 1;
	let date = dateObj.getDate();
	let cookiesId =
		"" +
		dateObj.getFullYear() +
		(month < 10 ? "0" + month : month) +
		(date < 10 ? "0" + date : date);
	// 加8位
	cookiesId += Math.round(Math.random() * 100000000);
	// 42位字母语与数字
	cookiesId += getRandomStr() + getRandomStr().substr(0, 10);
	return cookiesId;
}

function getSxUdid() { //获取视讯设备id
	var udidReq = {
		type: 'NATIVE_OUT_MESSAGEINFO',
		params: {
			path: '',
			frameID: '',
			contentID: '',
			location: 'WEB_VIEW_H5',
			pageID: '',
			url: '',
		}
	};
	try {
		bridge.fire('CallNative', udidReq, res => {
			store.commit('buryPoint/setSxUdid', res.deviceId || '');
			console.log('sxUdid:', store.state.buryPoint.sxUdid)
		});
	} catch (e) {
		//TODO handle the exception
	}
}


function getCartNum() {
	let cartAngle = store.state.shoppingCarNum;
	if (store.state.token && cartAngle != 0) {
		uni.setTabBarBadge({
			index: 2,
			text: cartAngle.toString()
		});
	} else {
		uni.removeTabBarBadge({
			index: 2
		});
	}
}

function getMgPath() {
	const mgpathList = {
		'product': 'https://m.migudm.cn/',
		'release': 'https://m.migudm.cn/ms_newwap/',
		'hotfix': 'http://112.48.155.28:28080/newwap_hotfix/',
		'text': 'http://112.48.155.28:28080/newwap_test/',
		'develop': 'http://112.48.155.28:28080/newwap_develop/'
	}
	return mgpathList[config.env]
}

//添加url参数
function appendParamsToUrl(url, params) {
	const _params = {};
	const urlArr = url.split("?");
	let resultUrl = urlArr[0].split("#")[0];
	let hash = url.split("#")[1] ? url.split("#")[1] : "";
	// 转换queryString
	if (urlArr[1]) {
		urlArr[1]
			.split("#")[0]
			.split("&")
			.forEach(item => {
				const pArr = item.split("=");
				_params[pArr[0]] = decodeURIComponent(pArr[1]);
			});
	}
	// 参数合并
	const paramKeys = Object.keys(Object.assign(_params, params));
	const paramArr = [];
	// query obj 转回 query string
	for (let i = 0; i < paramKeys.length; i++) {
		const k = paramKeys[i];
		paramArr.push(k + "=" + encodeURIComponent(_params[k]));
	}
	if (paramArr.length) {
		resultUrl += "?" + paramArr.join("&");
	}
	if (hash) {
		resultUrl += "#" + hash;
	}
	return resultUrl;
}

function navigateToWithSSO(url, addParam = {}, failLoginFn = null) {
	if (store.state.token) {
		// 登录状态则要同步登录
		let params = {
			passId: store.state.userInfoDetail.passId,
			usessionId: store.state.sessionId
		};
		// let mgPath = getMgPath()
		$request("user/login/getMiguSSOToken", params, 'api', false, false).then(res => {
			if (store.state.entrance == "mp-weixin") {
				getWxCode()
					.then(wxCode => {
						let webUrl = encodeURIComponent(
							appendParamsToUrl(url, Object.assign({
								wxCode: wxCode,
								token: res.token
							}, addParam))
						);
						routeUtils.navigateTo({
							url: "/pages/tools/webView?enCode=1&webUrl=" + webUrl
						});
					})
					.catch(e => {});
			} else {
				if (store.state.entrance == "app" && !store.state.isSDK) {
					if (url.match(/migudm\.cn.*pageType=webView/)) {
						window.location.href = appendParamsToUrl(url, {
							token: res.token
						});
					} else {
						let toUrl = appendParamsToUrl(url, {
							token: res.token
						})
						window.location.href =
							"https://m.migudm.cn?pageType=webView&url=" +
							encodeURIComponent(toUrl);
					}
				} else {
					routeUtils.locationTo(appendParamsToUrl(url, {
						token: res.token
					}))
				}
			}
		}, err => {
			if (store.state.entrance == "mp-weixin") {
				if (failLoginFn) {
					failLoginFn()
				} else {
					routeUtils.navigateTo({
						url: "/pages/tools/webView?enCode=1&webUrl=" + encodeURIComponent(url)
					});
				}
			} else if (store.state.entrance == "app" && !store.state.isSDK) {
				if (url.match(/migudm\.cn.*pageType=webView/)) {
					window.location.href = url
				} else {
					window.location.href =
						"https://m.migudm.cn?pageType=webView&url=" +
						encodeURIComponent(url);
				}
			} else {
				routeUtils.locationTo(url)
			}
		});
	} else {
		// 会员中心需要登录
		if (url.match(/\/spa\/member\/index.html/)) {
			login();
			return;
		}
		if (store.state.entrance == "mp-weixin") {
			var enCodeUrl = encodeURIComponent(url);
			routeUtils.navigateTo({
				url: "/pages/tools/webView?enCode=1&webUrl=" + enCodeUrl
			});
		} else {
			routeUtils.locationTo(url)
		}
	}
}
let emptyPriceWord = "暂时缺货";

function judgeStatusPrice(item) {
	let priceSign = {
		minVipPrice:item.minVipPrice&&parseFloat(item.minVipPrice / 100),//会员价格
		seckillPrice:item.activityType==2&&item.activityPrice&&parseFloat(item.activityPrice / 100),//秒杀价格
		price: item.minSalePrice, //显示价格
		delprice: item.minMarketPrice ? (item.minMarketPrice / 100).toFixed(2) : "", //划线价格
		priceSign: "", //价格标识 priceLable内购价 priceLable2会员价 priceLable3直供价
		activitySign: "", //活动标识 activityIcon-SecondsKill秒杀标识
		isMiguShop: "", //自营标识 spuType==1 “miguIcon”
		haveStock: 1, //区域是否有库存 0 无货 1有货
		activityType: "", //活动类型
		isEmpty: false, //是否抢空标示
		isShortage: false //是否缺货标示
	};
	let token = store.state.token; //判断是否登录
	// if (item.spuType && item.spuType === 1) {
	// 	priceSign.isMiguShop = "miguIcon";
	// }
	//假设活动字段是priceStatus 0销售价 1会员价 2内购价 3活动价
	switch (item.priceStatus) {
		case 1:
			priceSign.priceSign = "priceLable2";
			break;
		case 2:
			priceSign.priceSign = "priceLable";
			break;
		case 3:
			priceSign.priceSign = "";
			break;
	}

	// priceSign.price = item.minPrice;
	//未登录 or 登录不是会员
	// priceSign.price = priceSign.price ?(priceSign.price / 100).toFixed(2) : emptyPriceWord;
	if (priceSign.price) {
		priceSign.noPrice = false // 是不是没有价格，暂时缺货标识
		priceSign.price = parseFloat(priceSign.price / 100)
		
		// 有秒杀显示秒杀价，没秒杀，会员价和销售价取低显示
		const isVip = store.state.isVip;
		const { seckillPrice, price, minVipPrice } = priceSign;
		priceSign.price = seckillPrice || (
		  isVip && typeof minVipPrice === 'number' && price >= minVipPrice
		    ? minVipPrice
		    : price
		);
	} else {
		if (item.spuType != 3) {
			priceSign.noPrice = true
			priceSign.price = emptyPriceWord
		}
	}

	const priceStr = priceSign.price + "";
	if (priceStr.indexOf(".") !== -1) {
		const list = priceStr.split(".");
		priceSign.priceInt = list[0]
		priceSign.priceFloat = "." + list[1];
	} else {
		priceSign.priceInt = priceSign.price
	}

	if (priceSign.price < priceSign.delprice) {
		priceSign.delprice = parseFloat(priceSign.delprice);
	} else {
		priceSign.delprice = '';
	}
	priceSign.haveStock = item.haveStock;
	return priceSign;
}
//价格样式处理 当价格无小数点时，展示整数即可，举例：原￥148.00  展示￥148 当价格有小数点时，展示完整数，举例：￥148.28 展示￥148.28
function priceConversion(data, index) {
	let num = parseFloat(data / 100).toString();
	if (index == 0) {
		if (num == 'NaN') {
			return 0
		}
		if (num.split('.')[1] && num.split('.')[1] != 0) {
			return num.split('.')[index] + '.';
		}
		return num.split('.')[index];
	} else if (index == 1) {
		num = num.split('.')[index];
		if (parseFloat(num) == 0) { //小数点包含0，不展示
			return
		}
		return num ? num : ''
	} else {
		return parseFloat(num)
	}
	return num;
}

function queryUserJf() {
	return new Promise((resolve, reject) => {
		$request("product/queryUserJf", {}).then(data => {
			let userJf = parseInt(data.userJf || 0);
			resolve(userJf);
		});
	});
}

function syncDiandiOrderStockOut(orderId) { //点滴同步物流接口
	return new Promise((resolve, reject) => {
		$request("order/syncDiandiOrderStockOut", {
			id: orderId
		}, 'api', false, null, false).then(data => {
			resolve();
		}, err => {
			resolve();
		})
	});
}

function jumpToUser() {
	let params = {
		passId: store.state.userInfoDetail.passId,
		usessionId: store.state.sessionId
	};
	let mgPath = getMgPath();
	$request("user/login/getMiguSSOToken", params).then(res => {
		if (store.state.entrance == "app" && !store.state.isSDK) {
			window.location.href =
				"https://m.migudm.cn?pageType=webView&url=" +
				encodeURIComponent(
					mgPath +
					"spa/member/index.html?showRefreshOnly=1&mgtoken=" +
					res.token
				) +
				"&style=miniprogram&appId=b5f94fb0518c4486b03f072d254d2385";
		} else if (store.state.entrance == "mp-weixin") {
			getWxCode()
				.then(wxCode => {
					let webUrl = encodeURIComponent(
						mgPath +
						"spa/member/index.html?wxCode=" +
						wxCode +
						"&mgtoken=" +
						res.token
					);
					routeUtils.navigateTo({
						url: "/pages/tools/webView?enCode=1&webUrl=" + webUrl
					});
				})
				.catch(e => {});
		} else {
			routeUtils.locationTo(mgPath + "spa/member/index.html?mgtoken=" + res.token)
		}
	}, err => {
		if (store.state.entrance == "app" && !store.state.isSDK) {
			window.location.href =
				"https://m.migudm.cn?pageType=webView&url=" +
				encodeURIComponent(
					mgPath +
					"spa/member/index.html?showRefreshOnly=1"
				) +
				"&style=miniprogram&appId=b5f94fb0518c4486b03f072d254d2385";
		} else if (store.state.entrance == "mp-weixin") {
			getWxCode()
				.then(wxCode => {
					let webUrl = encodeURIComponent(
						mgPath +
						"spa/member/index.html?wxCode=" +
						wxCode
					);
					routeUtils.navigateTo({
						url: "/pages/tools/webView?enCode=1&webUrl=" + webUrl
					});
				})
				.catch(e => {});
		} else {
			routeUtils.locationTo(mgPath + "spa/member/index.html")
		}
	});
}

//获取当前时间，防止用户本地时间不准确
function getNowTime() {
	return $request("common/getSysTime", {});
}

//封装的new date（）方法，为了防止用户改变本地时区，而导致创建date对象不准的问题
function myNewDate(time) {
	if (time) {
		var timezone = 8; //目标时区时间，东八区
		var offset_GMT = new Date(time).getTimezoneOffset(); // 本地时间和格林威治的时间差，单位为分钟
		var nowDate = new Date(time).getTime(); // 本地时间距 1970 年 1 月 1 日午夜（GMT 时间）之间的毫秒数
		let date = new Date(
			nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000
		);
		return date;
	} else {
		return getNowTime();
	}
}

/**时间格式化
 * @param {Object} date 格式的时间，默认为当前时间
 * @param {Object} fmt 格式的时间格式，默认为YYYY-mm-dd HH:MM
 */
function dateFormat(date = new Date(), fmt = 'YYYY-mm-dd HH:MM') {
	let ret;
	const opt = {
		"Y+": date.getFullYear().toString(), // 年
		"m+": (date.getMonth() + 1).toString(), // 月
		"d+": date.getDate().toString(), // 日
		"H+": date.getHours().toString(), // 时
		"M+": date.getMinutes().toString(), // 分
		"S+": date.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt);
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		};
	};
	return fmt;
}


function getRect(selector, all, that) {
	return new Promise((resolve, reject) => {
		uni
			.createSelectorQuery()
			.in(that)[all ? "selectAll" : "select"](selector)
			.boundingClientRect(rect => {
				if (all && Array.isArray(rect) && rect.length) {
					resolve(rect);
				}
				if (!all && rect) {
					resolve(rect);
				}
				reject(rect)
			})
			.exec();
	});
}

/**获取图片信息
 * @param {Object} src
 */
function getImage(src) {
	return new Promise(resolve => {
		uni.getImageInfo({
			src: src,
			success: img => {
				resolve(img);
			}
		});
	});
}
/**
 * 是否是pc
 */
function IsPC() {
	var userAgentInfo = navigator.userAgent;
	var Agents = [
		"Android",
		"iPhone",
		"SymbianOS",
		"Windows Phone",
		"iPad",
		"iPod"
	];
	var flag = true;
	for (var v = 0; v < Agents.length; v++) {
		if (userAgentInfo.indexOf(Agents[v]) > 0) {
			flag = false;
			break;
		}
	}
	return flag;
}
/**
 * 获取url中的查询参数
 * @param sHref
 * @param sArgName
 * @returns {string}
 * @constructor
 */
function GetArgsFromHref(currentUrl = window.location.href) {
	let args = currentUrl.split("?");
	const retval = {};
	if (args[0] === currentUrl) {
		return retval;
	}
	let str = args[1];
	args = str.split("&");
	for (let i = 0; i < args.length; i++) {
		str = args[i];
		const arg = str.split("=");
		retval[arg[0]] = arg[1];
	}
	return retval;
}
/**
 * 去除Url token
 * @param {Object} url
 */
function removeLoginToken(url = window.location.href) {
	let orgArgs = url.split('?');
	var retval = {};
	if (orgArgs[0] === url) {} else {
		retval = GetArgsFromHref(url);
		for (var key in retval) {
			if (key != 'miguToken' && key != 'mgtoken' && key != 'token') {
				if (orgArgs[0].indexOf('?') >= 0) {
					orgArgs[0] = orgArgs[0] + '&' + key + '=' + retval[key];
				} else {
					orgArgs[0] = orgArgs[0] + '?' + key + '=' + retval[key];
				}
			}
		}
	}
	return orgArgs[0];
}
/**
 * H5中判断是否是PC，是的话跳转PC页面
 */
function ifNavigatePC() {
	const isPc = IsPC();
	if (isPc && GetArgsFromHref().isPCIframe !== "1") {
		const href = window.location.href;
		if (
			href.indexOf("isPCIframe") !== -1 ||
			href.indexOf("index_PC.html") !== -1
		)
			return;
		const channel = window.__channelId
		const removeChannelHref = href.replace(/(_[^\/]*\/)/g, '')
		const pageIndex = href.indexOf("/_");
		const beforeHref = href.slice(0, pageIndex)
		if (pageIndex !== -1) {
			window.location.href = beforeHref + "/index_PC.html?page=" + href.slice(pageIndex);
		} else if (href.substr(href.length - 1, 1) == "/") {
			window.location.href = beforeHref + "index_PC.html?page=/" + channel;
		}
	}
	return isPc;
}

// 获取32位随机字符串
function getNonce(length = 32) {
	let nonceStr = "";
	let strArr = "abcdefghigklmnopqrstuvwxyz0123456789";
	let strNum = strArr.length;
	for (var i = 0; i < length; i++) {
		let index = Math.floor(Math.random() * strNum);
		nonceStr += strArr[index];
	}
	return nonceStr;
}

function _queryDefaultAddress() {
	if (store.state.token) {
		return new Promise((resolve, reject) => {
			$request('user/address/getDefaultAddress', {}).then(res => {
				let addressInfo = res.address;
				let cityCode = null;
				if (addressInfo) {
					//有默认地址
					cityCode = {
						pickerId: [addressInfo.provinceId, addressInfo.cityId, addressInfo
							.districtId, addressInfo.townId || ''
						],
						pickerValue: [addressInfo.provinceName, addressInfo.cityName, addressInfo
							.districtName, addressInfo.townName || ''
						],
						ngocCode: [addressInfo.provinceCode, addressInfo.cityCode, addressInfo
							.districtCode, addressInfo.townCode || ''
						],
						detailAdress: addressInfo.detailedAddr || '',
						userId: store.state.userInfoDetail.mobile
					};
				}
				resolve(cityCode);
			});
		});
	}
}
//设置查询地址
async function setQueryAddress() {
	let goodsCity = uni.getStorageSync('eoc-good-city'); //缓存地址
	let cityInfoCode = !goodsCity ? await this._queryDefaultAddress() : {};
	cityInfoCode = cityInfoCode ? cityInfoCode : store.state.cityInfo.default;
	if (goodsCity) cityInfoCode = goodsCity;
	cityInfoCode.userId = store.state.userInfoDetail.mobile || null;
	uni.setStorageSync('eoc-good-city', cityInfoCode);
}
/**
 * @param {Object} type mediaPause播放 mediaPlay暂停 mediaEnd结束
 */
function videoBridge(type) {
	try {
		if (store.state.isSDK) {
			bridge.fire(type, {}, res => {});
		}
	} catch (e) {
		//TODO handle the exception
	}
}
/**DES解密
 * @param {Object} msg
 */
function DESdecrypt(msg) {
	const decrypt = cryptoJs.DES.decrypt(msg.replace(/\s/g, ''), cryptoJs.enc.Utf8.parse('migu-mall'), {
		mode: cryptoJs.mode.ECB,
		padding: cryptoJs.pad.Pkcs7
	}).toString(cryptoJs.enc.Utf8);
	return JSON.parse(decrypt)
}
/**DES加密
 * @param {Object} msg
 */
function encryptDes(message) {
	let msg = JSON.stringify(message)
	const keyHex = cryptoJs.enc.Utf8.parse('migu-mall')
	const option = {
		mode: cryptoJs.mode.ECB,
		padding: cryptoJs.pad.Pkcs7
	}
	let encrypted = cryptoJs.DES.encrypt(msg, keyHex, option)
	return encrypted.toString()
}

function base64Encrypt(val) {
	const str = cryptoJs.enc.Utf8.parse(val);
	const base64 = cryptoJs.enc.Base64.stringify(str);
	return base64
}

/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
function Debounce (fn, t) {
	let delay = t || 500;
	let timer;
	// console.log(fn)
	// console.log(typeof fn)
	return function() {
		let args = arguments;
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(() => {
			timer = null;
			fn.apply(this, args);
		}, delay);
	}
};
/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
function Throttle (fn, t, exposure, exposureTime = 500) {
	let last;
	let timer;
	let exposureTimer;
	let interval = t || 500;
	return function() {
		let args = arguments;
		let now = +new Date();
		if (last && now - last < interval) {
			clearTimeout(timer);
			timer = setTimeout(() => {
				last = now;
				fn.apply(this, args);
			}, interval);
		} else {
			last = now;
			fn.apply(this, args);
		}
		if (exposure) {
			if (exposureTimer) clearTimeout(exposureTimer)
			exposureTimer = setTimeout(() => {
				exposure.checkProductInWin(args)
			}, exposureTime)
		}
	}
};


/**
 * 跳转咪咕视讯app
 * pageID: 指定页面ID
*/
function goToMgVideo(pageID) {
	const openTime = +new Date();
	if (pageID) {
		let t = { pageID }
		var e = {};
		e.type = t.type,
		e.params = t.params || {},
		e.params.pageID = t.pageID || "",
		e.type = "JUMP_INNER_NEW_PAGE"

		location.href = "miguvideo://miguvideo?action=" + encodeURIComponent(JSON.stringify(e))
	} else{
		location.href = "miguvideo://miguvideo?"
	}
	let timer = setTimeout(function () {
		if ((new Date()) - openTime > 2200) {
			clearTimeout(timer);
		}
		if ((new Date()) - openTime < 2200) { //加了200ms基准误差
			// window.location.href = 'https://itunes.apple.com/cn/app/id787130974?mt=8';
			location.href = 'https://m.miguvideo.com/mgs/share/yyb/prd/direction.html?pageId=51e3d088bbfa489e818462a9d84167ff'
		}
	}, 2000);
}
/**
 * 对象深拷贝
 * @param {} o
 */
const deepCopy = o => {
  if (o instanceof Function) {
    return o
  } else if (o instanceof Array) {
    var array = []
    for (var i = 0; i < o.length; ++i) {
      array[i] = deepCopy(o[i])
    }
    return array
  } else if (o instanceof Date) {
    return new Date(o.valueOf())
  } else if (o instanceof Object) {
    var obj = {}
    for (var j in o) {
      obj[j] = deepCopy(o[j])
    }
    return obj
  } else {
    return o
  }
}

function deleteNullData(formData) {
  Object.keys(formData).forEach(item=>{
    if(isEmpty(formData[item])) {
      delete formData[item];
    }
  })
  return formData;

	function isEmpty(obj) {
	  if (typeof obj === 'undefined' || obj === null || obj === '') return true;
	  return false
	}
}
// 管理员-admin，部门-dept，专家-professional，企业-enterprise，经理人-manager
function identifyingCName (type){
	if(type === 'admin') {
		return '管理员'
	} else if (type === 'dept') {
		return '部门'
	} else if (type === 'professional') {
		return '专家'
	} else if (type === 'enterprise') {
		return '企业'
	} else if (type === 'manager') {
		return '经理人'
	} else {
		return '游客'
	}
}

export default {
	toast,
	sha256,
	handleLink,
	logout,
	isPhoneNumber,
	isPostcode,
	formatNum,
	formatTime,
	getWxCode,
	setSession,
	getSession,
	clearSession,
	canvasDataURL,
	backFresh,
	getRandomStr,
	generCookieId,
	appendParamsToUrl,
	checkWxScroll,
	getMgPath,
	jumpToUser,
	judgeStatusPrice,
	priceConversion,
	getNowTime,
	myNewDate,
	getCartNum,
	queryUserJf,
	isEmail,
	getRect,
	getImage,
	IsPC,
	GetArgsFromHref,
	removeLoginToken,
	ifNavigatePC,
	dateFormat,
	getNonce,
	navigateToWithSSO,
	syncDiandiOrderStockOut,
	setQueryAddress,
	_queryDefaultAddress,
	DESdecrypt,
	encryptDes,
	getSxUdid,
	videoBridge,
	base64Encrypt,
	Debounce,
	Throttle,
	goToMgVideo,
	deepCopy,
	deleteNullData,
	identifyingCName
};
